package cn.qidd.keep.manage.service.system.impl;

import cn.qidd.keep.domain.core.Constants;
import cn.qidd.keep.domain.core.dict.DeptProperty;
import cn.qidd.keep.domain.core.dict.DeptType;
import cn.qidd.keep.domain.document.Department;
import cn.qidd.keep.domain.util.ShortUUID;
import cn.qidd.keep.domain.web.BusinessException;
import cn.qidd.keep.manage.service.system.DepartmentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by sunyanping on 2018/9/17
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Override
    public void checkDeptProperty(Department pDept, DeptProperty childDeptProperty) {
        if (pDept.getDeptProperty() != null) {
            if (pDept.getDeptProperty() == DeptProperty.OUT) {
                if (childDeptProperty == DeptProperty.IN) {
                    throw new BusinessException("外部机构下只能创建外部机构");
                }
            }
        }
    }

    @Override
    public void checkDeptType(Department pDept, DeptType childDeptType) {
        DeptType pDeptType = pDept.getDeptType();
        if (StringUtils.equals(pDept.getId(), Constants.ADMINISTRATOR_DEPARTMENT_ID)) {
            throw new BusinessException("顶级机构下只能有一个机构节点");
        }
        if (StringUtils.isBlank(pDept.getDeptPid())) {
            if (childDeptType != DeptType.COMPANY) throw new BusinessException("顶级机构下只能创建总公司");
        }
        if (pDeptType == DeptType.COMPANY) {
            if (childDeptType == DeptType.COMPANY) throw new BusinessException("总公司下只能创建分公司或部门");
        }
        if (pDeptType == DeptType.PART_COMPANY) {
            if (childDeptType != DeptType.DEPARTMENT) throw new BusinessException("分公司下只能创建部门");
        }
        if (pDeptType == DeptType.DEPARTMENT) {
            if (childDeptType != DeptType.DEPARTMENT) throw new BusinessException("部门下只能创建部门");
        }
    }

    @Override
    public String generateDeptCode(String pDeptCode) {
        return pDeptCode.concat("_").concat(ShortUUID.generateShortUuid());
    }
}
